<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app"></div>
<script src="../../lib/js/react.development.js"></script>
<script src="../../lib/js/react-dom.development.js"></script>
<script src="../../lib/js/babel.min.js"></script>
<script type="text/javascript" src="../../lib/js/prop-types.js"></script>
<script type="text/babel">

    class App extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                todos: ['a', 'b', 'c']
            }
            this.addTodo = this.addTodo.bind(this)
        }

        addTodo(todo) {
            console.log("add todo "+ todo)
            let todos = this.state.todos;
            todos.unshift(todo)
            // 必须这样赋值
            this.setState({todos})
        }

        render() {
            return (
                <div>
                    <h1>todo list</h1>
                    <Add count={this.state.todos.length} addTodo={this.addTodo} />
                    <List todos={this.state.todos} />
                </div>
            )
        }
    }

    class Add extends React.Component {
        constructor(props) {
            super(props)
            this.add = this.add.bind(this)
        }

        add() {
            const value = this.todoDom.value;
            this.props.addTodo(value)
            this.todoDom.value=''
        }

        render() {
            const {count} = this.props
            return (
                <div>
                    <input type="text" ref={input => this.todoDom = input} />
                    <button onClick={this.add} >ADD#{count}</button>
                </div>
            )
        }
    }

    Add.propTypes = {
        count: PropTypes.number.isRequired,
        addTodo: PropTypes.func.isRequired
    }

    class List extends React.Component {
        constructor(props) {
            super(props)
        }

        render() {
            const {todos} = this.props
            return (
                <ul>
                    {
                        todos.map((todo, index) => <li key={index}>{todo}</li>)
                    }
                </ul>
            )
        }
    }
    List.propTypes = {
        todos: PropTypes.array.isRequired
    }
    ReactDOM.render(<App />, document.getElementById('app'))
</script>
</body>
</html>
